import { instance } from '@/api/shared'
import type { Resp } from '@/api/shared/type'

export type ZtrustScore = {
    cybertwin_id: number
    basic_score: number
    dynamic_score: number
}

export type ZtrustEvent = {
    id: number
    cybertwin_id: number
    event: string
    score_desc: string
    event_desc: string
    trigger_at: string // ISO 时间字符串
}

export async function GetAllZtrustScores(): Promise<Resp> {
    try {
        const res = await instance.get('/ztrust/scores')
        return res.data
    } catch (error) {
        console.error('获取零信任评分失败:', error)
        // 返回模拟数据用于开发测试
        return {
            code: 200,
            message: 'success',
            data: generateMockData()
        }
    }
}

export async function GetAllZtrustEvents(): Promise<Resp> {
    try {
        const res = await instance.get('/ztrust/events')
        return res.data
    } catch (error) {
        console.error('获取零信任事件失败:', error)
        // 返回模拟数据用于开发测试
        return {
            code: 200,
            message: 'success',
            data: generateMockEventData()
        }
    }
}

export async function GetZtrustEventsByCybertwinId(cybertwinId: number): Promise<Resp> {
    try {
        const res = await instance.get(`/ztrust/events/${cybertwinId}`)
        return res.data
    } catch (error) {
        console.error(`获取Cybertwin ${cybertwinId} 的零信任事件失败:`, error)
        // 返回模拟数据用于开发测试
        return {
            code: 200,
            message: 'success',
            data: generateMockEventDataByCybertwinId(cybertwinId)
        }
    }
}

// 生成模拟数据用于开发测试
function generateMockData(): ZtrustScore[] {
    const mockData: ZtrustScore[] = []

    for (let i = 1; i <= 50; i++) {
        mockData.push({
            cybertwin_id: 1000 + i,
            basic_score: Math.floor(Math.random() * 100),
            dynamic_score: Math.floor(Math.random() * 100)
        })
    }

    return mockData
}

// 生成事件模拟数据
function generateMockEventData(): ZtrustEvent[] {
    const mockData: ZtrustEvent[] = []
    const events = ['REDUCE', 'INCREASE', 'CREATE'] // 添加CREATE事件类型

    // 真实的事件描述（基于core.go中的定义）
    const eventDescriptions = [
        '访问控制告警：Cybertwin %d 可能正在尝试访问未授权资源',
        'DDoS 攻击告警：Cybertwin %d 可能正在发起 DDoS 攻击',
        '微服务调用链告警：Cybertwin %d 触发了非法的微服务调用链',
        '内核函数调用链告警：Cybertwin %d 触发了非法的内核函数调用链',
        '基于时间上调动态信任评级',
        '基于合法操作上调基础信任评级',
        '创建 Cybertwin，初始化信任评级' // CREATE事件描述
    ]

    for (let i = 1; i <= 100; i++) {
        const event = events[Math.floor(Math.random() * events.length)]
        const cybertwinId = 1000 + Math.floor(Math.random() * 50) + 1

        // 生成时间（最近30天内的随机时间）
        const now = new Date()
        const thirtyDaysAgo = new Date(now.getTime() - 30 * 24 * 60 * 60 * 1000)
        const randomTime = new Date(thirtyDaysAgo.getTime() + Math.random() * (now.getTime() - thirtyDaysAgo.getTime()))

        // 生成真实的分数变化描述
        let scoreDesc: string
        let eventDesc: string

        if (event === 'REDUCE') {
            const oldBasic = Math.floor(Math.random() * 40) + 60 // 60-100
            const newBasic = Math.floor(Math.random() * 30) + 30 // 30-60
            const oldDynamic = Math.floor(Math.random() * 40) + 60
            const newDynamic = Math.floor(Math.random() * 30) + 30

            scoreDesc = `基础信任评级由 ${oldBasic}.00 降低至 ${newBasic}.00, 动态信任评级由 ${oldDynamic}.00 降低至 ${newDynamic}.00`

            // 随机选择一个减少事件的描述
            const reduceDescs = eventDescriptions.slice(0, 4)
            eventDesc = reduceDescs[Math.floor(Math.random() * reduceDescs.length)].replace('%d', cybertwinId.toString())
        } else if (event === 'INCREASE') {
            const oldScore = Math.floor(Math.random() * 40) + 30 // 30-70
            const newScore = Math.floor(Math.random() * 30) + 70 // 70-100
            const isBasic = Math.random() > 0.5

            if (isBasic) {
                scoreDesc = `基础信任评级由 ${oldScore}.00 上调至 ${newScore}.00`
                eventDesc = eventDescriptions[5] // 基于合法操作上调基础信任评级
            } else {
                scoreDesc = `动态信任评级由 ${oldScore}.00 上调至 ${newScore}.00`
                eventDesc = eventDescriptions[4] // 基于时间上调动态信任评级
            }
        } else { // CREATE事件
            const basicScore = Math.floor(Math.random() * 100) // 0-100
            const dynamicScore = Math.floor(Math.random() * 100) // 0-100

            scoreDesc = `创建 Cybertwin ${cybertwinId}，初始化基础信任评级为 ${(basicScore / 10000).toFixed(2)}，动态信任评级为 ${(dynamicScore / 10000).toFixed(2)}`
            eventDesc = eventDescriptions[6] // 创建 Cybertwin，初始化信任评级
        }

        mockData.push({
            id: i,
            cybertwin_id: cybertwinId,
            event: event,
            score_desc: scoreDesc,
            event_desc: eventDesc,
            trigger_at: randomTime.toISOString()
        })
    }

    return mockData.sort((a, b) => new Date(b.trigger_at).getTime() - new Date(a.trigger_at).getTime())
}

// 根据cybertwin_id生成事件模拟数据
function generateMockEventDataByCybertwinId(cybertwinId: number): ZtrustEvent[] {
    const mockData: ZtrustEvent[] = []
    const events = ['REDUCE', 'INCREASE', 'CREATE'] // 添加CREATE事件类型

    // 真实的事件描述（基于core.go中的定义）
    const eventDescriptions = [
        '访问控制告警：Cybertwin %d 可能正在尝试访问未授权资源',
        'DDoS 攻击告警：Cybertwin %d 可能正在发起 DDoS 攻击',
        '微服务调用链告警：Cybertwin %d 触发了非法的微服务调用链',
        '内核函数调用链告警：Cybertwin %d 触发了非法的内核函数调用链',
        '基于时间上调动态信任评级',
        '基于合法操作上调基础信任评级',
        '创建 Cybertwin，初始化信任评级' // CREATE事件描述
    ]

    // 为指定cybertwin生成10-20个事件
    const eventCount = Math.floor(Math.random() * 11) + 10 // 10-20个事件

    for (let i = 1; i <= eventCount; i++) {
        const event = events[Math.floor(Math.random() * events.length)]

        // 生成时间（最近30天内的随机时间）
        const now = new Date()
        const thirtyDaysAgo = new Date(now.getTime() - 30 * 24 * 60 * 60 * 1000)
        const randomTime = new Date(thirtyDaysAgo.getTime() + Math.random() * (now.getTime() - thirtyDaysAgo.getTime()))

        // 生成真实的分数变化描述
        let scoreDesc: string
        let eventDesc: string

        if (event === 'REDUCE') {
            const oldBasic = Math.floor(Math.random() * 40) + 60 // 60-100
            const newBasic = Math.floor(Math.random() * 30) + 30 // 30-60
            const oldDynamic = Math.floor(Math.random() * 40) + 60
            const newDynamic = Math.floor(Math.random() * 30) + 30

            scoreDesc = `基础信任评级由 ${oldBasic}.00 降低至 ${newBasic}.00, 动态信任评级由 ${oldDynamic}.00 降低至 ${newDynamic}.00`

            // 随机选择一个减少事件的描述
            const reduceDescs = eventDescriptions.slice(0, 4)
            eventDesc = reduceDescs[Math.floor(Math.random() * reduceDescs.length)].replace('%d', cybertwinId.toString())
        } else if (event === 'INCREASE') {
            const oldScore = Math.floor(Math.random() * 40) + 30 // 30-70
            const newScore = Math.floor(Math.random() * 30) + 70 // 70-100
            const isBasic = Math.random() > 0.5

            if (isBasic) {
                scoreDesc = `基础信任评级由 ${oldScore}.00 上调至 ${newScore}.00`
                eventDesc = eventDescriptions[5] // 基于合法操作上调基础信任评级
            } else {
                scoreDesc = `动态信任评级由 ${oldScore}.00 上调至 ${newScore}.00`
                eventDesc = eventDescriptions[4] // 基于时间上调动态信任评级
            }
        } else { // CREATE事件
            const basicScore = Math.floor(Math.random() * 100) // 0-100
            const dynamicScore = Math.floor(Math.random() * 100) // 0-100

            scoreDesc = `创建 Cybertwin ${cybertwinId}，初始化基础信任评级为 ${(basicScore / 10000).toFixed(2)}，动态信任评级为 ${(dynamicScore / 10000).toFixed(2)}`
            eventDesc = eventDescriptions[6] // 创建 Cybertwin，初始化信任评级
        }

        mockData.push({
            id: 1000 + i,
            cybertwin_id: cybertwinId,
            event: event,
            score_desc: scoreDesc,
            event_desc: eventDesc,
            trigger_at: randomTime.toISOString()
        })
    }

    return mockData.sort((a, b) => new Date(b.trigger_at).getTime() - new Date(a.trigger_at).getTime())
}
